import router from "@/router";
import { defineComponent, reactive, ref } from "vue";
import { API, requests } from "../../api";
import "./login.less";

export default defineComponent({
  setup() {
    const user = {
      model: reactive({
        username: "",
        password: "",
      }),
      login: () => {
        if (user.model.username.length < 6) {
          username.value = 1;
          return false;
        } else {
          username.value = 0;
        }
        if (user.model.password.length < 6) {
          password.value = 1;
          return false;
        } else {
          password.value = 0;
        }
        doRequest();
      },
    };
    const username = ref(0);
    const password = ref(0);
    const doRequest = () => {
      requests({
        url: API.user.login,
        data: user.model,
      }).then((res: any) => {
        if(res.code == -1){
          alert("账号或者密码错误!");
          return false;
        }
        if (res.code == 0) {
          sessionStorage.setItem("token",res.results[0].token);
          router.push("/");
        }
      });
    };

    return () => (
      <>
        <div class="login bg-heise w-full h-screen flex justify-center items-center">
          <div class="w-6/12 h-1/2">
            <div class=" text-tw text-center text-xl mt-8 h-20">
              你的账号:<input type="text" v-model={user.model.username} name="username" class="border rounded mx-8 w-80 h-10 text-tp text-center" />
              <br />
              <span class="text-sm text-hongse"><span v-show={username.value == 1 ? true : false}>账号不能低于6位数</span></span>
            </div>
            <div class=" text-tw text-center text-xl h-20">
              你的密码:<input type="password" v-model={user.model.password} name="password" class="border rounded mx-8 w-80 h-10 mt-8 text-tp text-center"/>
              <br />
              <span class="text-sm text-hongse" v-show={password.value == 1 ? true : false}>密码不能低于6位数</span>
            </div>
            <button class="bg-tw border-0 w-32 h-10 block mx-auto mt-20 rounded" onClick={user.login}>登陆</button>
          </div>
        </div>
      </>
    );
  },
});
